<%= alchemy_form_for([:admin, node], id: "node_form") do |f| %>
  <% if node.new_record? && node.root? %>
    <%= f.input :menu_type,
      collection: Alchemy::Current.language.available_menu_names.map { |n| [I18n.t(n, scope: [:alchemy, :menu_names]), n] },
      include_blank: false,
      input_html: { is: 'alchemy-select' } %>
  <% else %>
    <% if node.root? %>
      <%= f.input :name %>
    <% else %>
      <%= f.input :name, input_html: {
        autofocus: true,
        value: node.page && node.read_attribute(:name).blank? ? nil : node.name,
        placeholder: node.page ? node.page.name : nil
      } %>
      <%= render Alchemy::Admin::PageSelect.new(node.page, allow_clear: true, query_params: {contentpages: true}) do %>
        <%= f.input :page_id, label: Alchemy::Page.model_name.human %>
      <% end %>
      <%= f.input :url, as: :string, input_html: {
          disabled: node.page,
          pattern: '/.*|[a-zA-Z][\w\+\-\.]*://.+',
          title: Alchemy.t(:node_url_hint)
        }, hint: Alchemy.t(:node_url_hint) %>
      <%= f.input :title %>
      <%= f.input :nofollow %>
      <%= f.input :external %>
      <%= f.hidden_field :parent_id %>
    <% end %>
  <% end %>
  <%= f.hidden_field :language_id %>
  <%= f.submit button_label %>
<% end %>

<script type="module">
  const nodeName = document.getElementById("node_name")
  const nodeUrl = document.getElementById("node_url")
  const form = document.getElementById("node_form")

  form.addEventListener("Alchemy.RemoteSelect.Change", (event) => {
    const page = event.detail.added

    if (page) {
      nodeName.setAttribute("placeholder", page.name)
      nodeUrl.value = page.url_path
      nodeUrl.setAttribute("disabled", "disabled")
    } else {
      nodeName.removeAttribute("placeholder")
      nodeUrl.value = ""
      nodeUrl.removeAttribute("disabled")
    }
  })
</script>
